<?php

namespace App\Models\Customer;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

/**
 * Class Language
 *
 * @mixin Builder
 * @mixin \Illuminate\Database\Query\Builder
 *
 * @package App\Models\Customer
 */
class Language extends Model
{
    protected $table = 'languages';
    protected $guarded = [];

    // 定义的常量
    const ZH_CN = "zh-CN";
    const EN = "en";
    const ZH_HK = 'zh-HK';

    const LANGUAGE_ID_CN = 1;
    const LANGUAGE_ID_HK = 2;
    const LANGUAGE_ID_EN = 3;

    /**
     * @return array
     */
    public static function getLanguageIds()
    {
        return (new self)->all()
            ->pluck('id', 'code')
            ->toArray();
    }

    /**
     * @param $code
     * @return int
     */
    public static function mapCodeToId($code): int
    {
        $code_id_map = (new self)
            ->pluck('id', 'code')
            ->all();

        $language_id = $code_id_map[$code]
            ?? $code_id_map[self::ZH_CN]
            ?? head($code_id_map);

        return $language_id;
    }

    /**
     * @param $language_id
     * @return mixed
     */
    public static function getLanguageCode($language_id)
    {
        $language_id = $language_id ?? self::LANGUAGE_ID_CN;

        $language = (Language::find($language_id)) ?? (Language::first());

        $language_code = $language->code;

        return $language_code;
    }
}
